{*
  Object Pascal simple colour manipulation routines
  @Author  Maciej Zagozda (1998-2008)
  @Licence Microsoft Reciprocal License (Ms-RL)
  @Website http://www.codeplex.com/intelitechdelphirtns/
  @Version 2008/04/20 Added documentation support
}

unit ColorRoutines;

interface

uses
  Classes,
  Clipbrd,
  Controls,
  Dialogs,                
  ExtCtrls,
  Forms,
  Graphics,
  Messages,
  SysUtils,
  Windows;

function GetHTMLColor( colorDefault: TColor ): ShortString;
function GetLightColor(ABtnFaceColorPart, AHighlightColorPart, AWindowColorPart: Integer): COLORREF;
function GetRealColor(AColor: COLORREF): COLORREF;
function GetXPSelectedColor: COLORREF;

implementation

function GetHTMLColor( colorDefault: TColor ): ShortString;
  function IntToHexStr(const Value: integer): string;
  begin
    Result := Format('#%.6x', [Value]);
  end;

  function D2HTMLColor(DColor: TColor): TColor;
  begin
    Result := (DColor and $0000FF00) or ((DColor mod $100) * $10000)
      or ((DColor div $10000) mod $100);
  end;
begin  
  Result := IntToHexStr( D2HTMLColor( colorDefault ));
end;

function GetLightColor(ABtnFaceColorPart, AHighlightColorPart, AWindowColorPart: Integer): COLORREF;
var
  ABtnFaceColor, AHighlightColor, AWindowColor: COLORREF;

  function GetLightIndex(ABtnFaceValue, AHighlightValue, AWindowValue: Byte): Integer;
  begin
    Result :=
      MulDiv(ABtnFaceValue, ABtnFaceColorPart, 100) +
      MulDiv(AHighlightValue, AHighlightColorPart, 100) +
      MulDiv(AWindowValue, AWindowColorPart, 100);
    if Result < 0 then Result := 0;
    if Result > 255 then Result := 255;
  end;

begin
  ABtnFaceColor := GetSysColor(COLOR_BTNFACE);
  AHighlightColor := GetSysColor(COLOR_HIGHLIGHT);
  AWindowColor := GetSysColor(COLOR_WINDOW);
  if (ABtnFaceColor = 0) or (ABtnFaceColor = $FFFFFF) then
    Result := AHighlightColor
  else
    Result := RGB(
      GetLightIndex(GetRValue(ABtnFaceColor), GetRValue(AHighlightColor), GetRValue(AWindowColor)),
      GetLightIndex(GetGValue(ABtnFaceColor), GetGValue(AHighlightColor), GetGValue(AWindowColor)),
      GetLightIndex(GetBValue(ABtnFaceColor), GetBValue(AHighlightColor), GetBValue(AWindowColor)));
end;

function GetRealColor(AColor: COLORREF): COLORREF;
var
  DC: HDC;
begin
  DC := GetDC(0);
  Result := GetNearestColor(DC, AColor);
  ReleaseDC(0, DC);
end;

function GetXPSelectedColor: COLORREF;
begin
  Result := GetRealColor(GetLightColor(-2, 30, 72));
end;
end.
